package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
  @Resource
    IBlogService blogService;
    @Resource
    private IUserService userService;
    @Override
    public Result queryHotBlog(Integer current, HttpServletRequest request) {
        // 根据用户查询,点赞排行
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();

        String token = request.getHeader("authorization");
        Object id =  stringRedisTemplate.opsForHash().get(LOGIN_USER_KEY + token, "id");
        if(id==null){
            records.forEach(blog ->{
                Long userId = blog.getUserId();
                User user = userService.getById(userId);
                blog.setName(user.getNickName());
                blog.setIcon(user.getIcon());
            });
            return Result.ok(records);
        }else {
            records.forEach(blog -> {
                String Id = blog.getId().toString();
                //每个博客都判断当前登录的用户有没有点赞:
                Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + Id, id.toString());
                blog.setIsLike(score!=null);
                User user = userService.getById(blog.getUserId());
                blog.setName(user.getNickName());
                blog.setIcon(user.getIcon());
            });
            return Result.ok(records);
        }
    }
    @Override
    public Result likeBlog(Long id) {
        // 1.获取登录用户
        Long userID = UserHolder.getUser().getId();
        // 2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userID.toString());

        // 3.如果未点赞，可以点赞
        if(score == null){
            // 3.1.数据库点赞数
            update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2.保存用户到Redis的set集合  zadd key value score
        //System.currentTimeMillis()时间戳，把用户点赞时间排名
        stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY + id, userID.toString(), System.currentTimeMillis());
        }else {
            // 4.如果已点赞，取消点赞
            // 4.1.数据库点赞数 -1
            update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2.把用户从Redis的set集合移除
            stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY + id, userID.toString());

        }
          return Result.ok();
    }

    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 2.查询blog有关的用户
        queryBlogUser(blog);
        // 3.查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

    }
    private void isBlogLiked(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
}
